<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Config;
use App\Services\ConfigService;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Controllers\AdminController;
use App\Models\Config as ConfigModel;
use Illuminate\Http\Request;

class ConfigController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new ConfigModel(), function (Grid $grid) {
            $grid->id->sortable();
            $grid->title;
            $grid->name;
            $grid->group;
            $grid->type->display(function ($type){
                return ConfigModel::TYPE[$type];
            });
            $grid->tip;
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();

                $filter->like('name')->width(2);
                $filter->like('group')->select(ConfigService::getGroup())->width(2);
                $filter->equal('type')->select(ConfigModel::TYPE)->width(2);
            });

            // 禁用详情按钮
            $grid->disableViewButton();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Config(), function (Show $show) {
            $show->id;
            $show->name;
            $show->group;
            $show->title;
            $show->tip;
            $show->type;
            $show->value;
            $show->content;
            $show->rule;
            ConfigService::refreshFile();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Config(), function (Form $form) {
            $form->display('id');
            if ($form->isCreating()) {
                $form->text('name', '变量名')->rules('unique:config,name')->required();
                $form->select('group', '分组')->options(ConfigService::getGroup())->required();
                $form->text('title', '变量标题')->required();
                $form->text('tip', '变量描述');
                $form->select('type', '选择类型')->options(ConfigModel::TYPE)->required();
                $form->text('value', '变量值');
                $form->textarea('content', '变量字典数据')->placeholder('示例：key|value');

                $form->saving(function (Form $form) {
                    $type = $form->input('type');
                    if($type == 'array'){
                        //校验格式
                        $content = $form->input('content');
                        $json = explode(PHP_EOL,$content);
                        if($json){
                            $array = [];
                            foreach ($json as $item){
                                $set = explode('|',$item);
                                if(count($set) == 2){
                                    $array[] = ['key'=>trim($set[0]),'value'=>trim($set[1])];
                                }
                            }
                            $form->value = json_encode($array,JSON_UNESCAPED_UNICODE);
                        }
                    }else{
                        $form->content = '';
                    }
                });
            }

            if ($form->isEditing()) {
                //获取配置信息
                $config = ConfigModel::select(['type','content','value'])->where('id',$form->getKey())->first();
                $form->text('name', '变量名')->required()->readOnly();
                $form->select('group', '分组')->options(ConfigService::getGroup())->required();
                $form->text('title', '变量标题')->required();
                $form->text('tip', '变量描述');
//                $form->select('type', '选择类型')->options(ConfigModel::TYPE)->readOnly();
                switch ($config->type){
                    case 'number': //数字
                        $form->number('value','变量值')->value($config->value);
                        break;
                    case 'radio': //单选
                        $form->radio('value','变量值')->options($config->content)->value($config->value);
                        break;
                    case 'checkbox': //多选
                        $form->checkbox('value','变量值')->options($config->content)->value($config->value);
                        break;
                    case 'select': //下拉单选
                        $form->select('value','变量值')->options($config->content)->value($config->value);
                        break;
                    case 'multipleSelect': //下拉多选
                        $form->multipleSelect('value','变量值')->options($config->content)->value($config->value);
                        break;
                    case 'array': //JSON
                        $form->table('value', function (Form\NestedForm $table){
                            $table->text('key','键名');
                            $table->text('value','键值');
                        })->value($config->value);
                        break;
                    case 'image': //单图
                        $form->image('value','变量值')->value($config->value)->removable();
                        break;
                    case 'multipleImage': //多图
                        $form->multipleImage('value','变量值')->value($config->value)->removable();
                        break;
                    case 'time': //时间
                        $form->time('value','变量值')->format('HH:mm:ss')->value($config->value);
                        break;
                    case 'date': //日期
                        $form->date('value','变量值')->format('YYYY-MM-DD')->value($config->value);
                        break;
                    case 'datetime': //日期时间
                        $form->datetime('value','变量值')->format('YYYY-MM-DD HH:mm:ss')->value($config->value);
                        break;
                    case 'text': //多行文本
                        $form->textarea('value','变量值')->rows(5);
                        break;
                    case 'editor': //富文本编辑
                        $form->editor('value','变量值')->value($config->value);
                        break;
                    case 'switch': //开关
                        $form->switch('value','变量值')->value($config->value);
                        break;
                    case 'mobile': //手机号
                        $form->mobile('value','变量值')->value($config->value);
                        break;
                    case 'url': //链接
                        $form->url('value','变量值')->value($config->value);
                        break;
                    case 'password': //密码
                        $form->password('value','变量值')->value($config->value);
                        break;
                    case 'email': //邮箱
                        $form->email('value','变量值')->value($config->value);
                        break;
                    case 'file': //单文件
                        $form->file('value','变量值')->value($config->value)->removable();
                        break;
                    case 'multipleFile': //多文件
                        $form->multipleFile('value','变量值')->value($config->value)->removable();
                        break;
                    default:
                        $form->text('value', '变量值');
                }
                if($config->type == 'array'){
                    $value = $form->input('value');
                    $array = [];
                    if($value){
                        foreach ($value as $k =>$v){
                            if(isset($v['_remove_']) && $v['_remove_'] == 1){
                                unset($value[$k]);
                                continue;
                            }
                            if($v['key'] && $v['value']){
                                $array[] = ['key'=>trim($v['key']),'value'=>trim($v['value'])];
                            }
                        }
                    }
                    $form->value = $array;

                    $form->saved(function (Form $form) use($config,$array) {
                        ConfigModel::where('id',$form->getKey())->update([
                            'value' => $array,
                            'content' => ''
                        ]);
                    });
                }
            }


            $form->tools(function (Form\Tools $tools) {
                // 去掉跳转列表按钮
                $tools->disableList();
            });

            $form->footer(function ($footer) {
                // 去掉`查看`checkbox
                $footer->disableViewCheck();
                // 去掉`继续编辑`checkbox
                $footer->disableEditingCheck();
            });

            ConfigService::refreshFile();
        });
    }
}
